<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types=1);

namespace app\cert\controller;

use app\base\BaseController;
use app\cert\model\declareTax;
use app\cert\model\declareTaxFinance;
use think\facade\Db;
use think\facade\View;

class Indexfinance extends BaseController
{
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();
            $whereOr = array();
            if (!empty($param['keywords'])) {
                $where[] = ['a.company_name', 'like', '%' . $param['keywords'] . '%'];
            }
            if (!empty($param['tax_name'])) {
                $where[] = ['a.tax_name', 'like', '%' . $param['tax_name'] . '%'];
            }
            if (!empty($param['company_type'])) {
                $where[] = ['a.company_type', '=',$param['company_type']];
            }
            if (!empty($param['type'])) {
                $where[] = ['a.type', '=',$param['type']];
            }
            $where[] = ['a.delete_time', '=', 0];
            if ($this->uid != 1 && $this->uid != 3) {
                $where[] = ['a.admin_id', '=', $this->uid];
            }

            $model = new declareTaxFinance();
            $list = $model->get_list($param, $where, $whereOr);
            return table_assign(0, '', $list);
        } else {

            return view();
        }
    }


    //添加&&编辑
    public function add()
    {
        $param = get_params();
        unset($param['file']);
        if (empty($param['sign_date'])) {
            unset($param['sign_date']);
        }

        if (request()->isAjax()) {
            if (!empty($param['id']) && $param['id'] > 0) {
                $isco = Db::name('declare_tax_finance')->where('id', '<>', $param['id'])->where('delete_time', 0)->where('company_name', $param['company_name'])->find();
                if (!empty($isco)) {
                    return to_assign(1, '已有该公司报税信息，请直接搜索');
                }
                $param['update_time'] = time();
                $old = Db::name('declare_tax_finance')->where(['id' => $param['id']])->find();
                $model = new declareTaxFinance();
                $res = $model->field(true)->update($param);
                if ($res) {
                    add_log('edit', $param['id'], $param);
                    to_log($this->uid, $param, $old);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            } else {
                $tax_pid = isset($param['tax_pid']) ? $param['tax_pid'] : 0;
                if ($tax_pid == 0) {
                    $isco = Db::name('declare_tax_finance')->where('delete_time', 0)->where('company_name', $param['company_name'])->find();
                    if (!empty($isco)) {
                        return to_assign(1, '已有该公司报税信息，请直接搜索');
                    }
                } else {
                    $isco = Db::name('declare_tax_finance')->where('delete_time', 0)->where('company_name', $param['company_name'])->find();
                    $param['pid'] = $isco['id'];
                }

                $param['create_time'] = time();
                $param['admin_id'] = $this->uid;
                $model = new declareTaxFinance();
                $aid = $model->field(true)->insertGetId($param);
                if ($aid) {
                    add_log('add', $aid, $param);
                    return to_assign();
                } else {
                    return to_assign(1, '操作失败');
                }
            }
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            if ($id > 0) {
                $model = new declareTaxFinance();
                $detail = $model->detail($id);
                View::assign('detail', $detail);
            }
            $tax_pid = isset($param['tax_pid']) ? $param['tax_pid'] : 0;
            View::assign('tax_pid', $tax_pid);
            if ($tax_pid > 0) {
                $model = new declareTaxFinance();
                $detail = $model->detail($tax_pid);
                View::assign('detail', $detail);
            }
            return view();
        }
    }

    //删除
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $data['id'] = $id;
            $data['delete_time'] = time();
            if (Db::name('declare_tax_finance')->update($data) !== false) {
                add_log('delete', $id);

                return to_assign(0, "删除成功");
            } else {
                return to_assign(1, "删除失败");
            }
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    //添加&&编辑
    public function view()
    {
        $param = get_params();
        unset($param['file']);
        unset($param['scene']);
        if (request()->isAjax()) {

        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            if ($id > 0) {
                $model = new declareTaxFinance();
                $detail = $model->detail($id);
                $detail['history'] = Db::name('declare_tax_finance')->where('delete_time', 0)->where('company_name', $detail['company_name'])->select()->toArray();
                View::assign('detail', $detail);
            }


            $flows = Db::name('FlowStep')->where(['action_id' => $detail['id'], 'type' => 23, 'sort' => $detail['check_step_sort'], 'delete_time' => 0])->find();
            $detail['check_user'] = '-';
            $detail['copy_user'] = '-';
            $check_user_ids = [];
            if ($detail['check_status'] == 1) {
                if ($flows['flow_type'] == 1) {
                    $detail['check_user'] = '部门负责人';
                    $check_user_ids[] = get_department_leader($detail['admin_id']);
                } else if ($flows['flow_type'] == 2) {
                    $detail['check_user'] = '上级部门负责人';
                    $check_user_ids[] = get_department_leader($detail['admin_id'], 1);
                } else {
                    $check_user_ids = explode(',', $flows['flow_uids']);
                    $check_user = Db::name('Admin')->where('id', 'in', $flows['flow_uids'])->column('name');
                    $detail['check_user'] = implode(',', $check_user);
                }
            }

            if ($detail['copy_uids'] != '') {
                $copy_user = Db::name('Admin')->where('id', 'in', $detail['copy_uids'])->column('name');
                $detail['copy_user'] = implode(',', $copy_user);
            }
            $is_check_admin = 0;
            $is_create_admin = 0;
            if ($detail['admin_id'] == $this->uid) {
                $is_create_admin = 1;
            }
            if (in_array($this->uid, $check_user_ids)) {
                $is_check_admin = 1;
                //当前审核节点详情
                if ($flows['flow_type'] == 4) {
                    $check_count = Db::name('FlowRecord')->where(['action_id' => $detail['id'], 'type' => 23, 'step_id' => $flows['id'], 'check_user_id' => $this->uid])->count();
                    if ($check_count > 0) {
                        $is_check_admin = 0;
                    }
                }
            }

            $check_record = Db::name('FlowRecord')->field('f.*,a.name,a.thumb')
                ->alias('f')
                ->join('Admin a', 'a.id = f.check_user_id', 'left')
                ->where(['f.action_id' => $detail['id'], 'f.type' => 23])
                ->order('check_time desc')
                ->select()->toArray();
            foreach ($check_record as $kk => &$vv) {
                $vv['check_time_str'] = date('Y-m-d H:i', $vv['check_time']);
                $vv['status_str'] = '提交';
                if ($vv['status'] == 1) {
                    $vv['status_str'] = '审核通过';
                } else if ($vv['status'] == 2) {
                    $vv['status_str'] = '审核拒绝';
                }
                if ($vv['status'] == 3) {
                    $vv['status_str'] = '撤销';
                }
            }

            View::assign('is_create_admin', $is_create_admin);
            View::assign('is_check_admin', $is_check_admin);
            View::assign('check_record', $check_record);
            View::assign('flows', $flows);
            View::assign('uid', $this->uid);

            return view();
        }
    }

    public function report()
    {
        $param = get_params();

        if (request()->isAjax()) {

            $param['check_status'] = 1;
            $param['check_step_sort'] = 0;
            $flow_list = Db::name('Flow')->where('id', $param['flow_id'])->value('flow_list');
            $flow = unserialize($flow_list);
            //删除原来的审核流程和审核记录
            Db::name('FlowStep')->where(['action_id' => $param['id'], 'type' => 23, 'delete_time' => 0])->update(['delete_time' => time()]);
            Db::name('FlowRecord')->where(['action_id' => $param['id'], 'type' => 23, 'delete_time' => 0])->update(['delete_time' => time()]);
            if (!isset($param['check_admin_ids'])) {
                if ($flow[0]['flow_type'] == 1) {
                    //部门负责人
                    $leader = get_department_leader($this->uid);
                    if ($leader == 0) {
                        return to_assign(1, '审批流程设置有问题：当前部门负责人还未设置，请联系HR或者管理员');
                    } else {
                        $param['check_admin_ids'] = $leader;
                    }
                } else if ($flow[0]['flow_type'] == 2) {
                    //上级部门负责人
                    $leader = get_department_leader($this->uid, 1);
                    if ($leader == 0) {
                        return to_assign(1, '审批流程设置有问题：上级部门负责人还未设置，请联系HR或者管理员');
                    } else {
                        $param['check_admin_ids'] = $leader;
                    }
                } else {
                    $param['check_admin_ids'] = $flow[0]['flow_uids'];
                }
                foreach ($flow as $key => &$value) {
                    $value['action_id'] = $param['id'];
                    $value['sort'] = $key;
                    $value['type'] = 23;
                    $value['create_time'] = time();
                }
                //增加审核流程
                Db::name('FlowStep')->strict(false)->field(true)->insertAll($flow);
            } else {
                $flow_step = array(
                    'action_id' => $param['id'],
                    'type' => 23,
                    'flow_uids' => $param['check_admin_ids'],
                    'create_time' => time()
                );
                //增加审核流程
                Db::name('FlowStep')->strict(false)->field(true)->insertGetId($flow_step);
            }
            $res = declareTaxFinance::where('id', $param['id'])->strict(false)->field(true)->update($param);
            if ($res !== false) {
                $appro['action_id'] = $param['id'];
                $appro['type'] = 40;
                $appro['start_time'] = time();
                $appro['admin_id'] = $this->uid;
                $appro['department_id'] = $this->did;
                $appro['create_time'] = time();
                $appro['flow_id'] = $param['flow_id'];
                $appro['check_admin_ids'] = $param['check_admin_ids'];
                $appro['copy_uids'] = $param['copy_uids'];
                $appro['check_status'] = $param['check_status'];
                if (empty(Db::name('Approve')->where('action_id', $appro['action_id'])->where('type', $appro['type'])->find())) {
                    Db::name('Approve')->strict(false)->field(true)->insertGetId($appro);
                } else {
                    Db::name('Approve')->where('action_id', $appro['action_id'])->where('type', $appro['type'])->strict(false)->field(true)->update($appro);
                }
                //添加提交申请记录
                $checkData = array(
                    'action_id' => $param['id'],
                    'check_user_id' => $this->uid,
                    'content' => '重新提交申请',
                    'type' => 23,
                    'check_time' => time(),
                    'create_time' => time()
                );
                $record_id = Db::name('FlowRecord')->strict(false)->field(true)->insertGetId($checkData);
                add_log('edit', $param['id'], $param);
                //发送消息通知
                $msg = [
                    'from_uid' => $this->uid,
                    'title' => '财务-报税',
                    'action_id' => $param['id']
                ];
                $users = $param['check_admin_ids'];
                sendMessage($users, 241, $msg);
                return to_assign();
            } else {
                return to_assign(1, '操作失败');
            }


        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            View::assign('id', $id);
            $department = $this->did;
            //获取发票审批流程
            $flows = get_type_department_flows(23, $department);
            View::assign('user', get_admin($this->uid));
            View::assign('flows', $flows);
            if ($id > 0) {
                $model = new declareTaxFinance();
                $detail = $model->detail($id);
                View::assign('detail', $detail);
            }
            return view();
        }
    }
}
